package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserMapper;
import com.heima.admin.service.UserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.UserVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserServiceImpl
 * @Description 登录服务实现类
 * @Author AWei
 * @DATE 2021/4/10 20:50
 * @Version 1.0
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, AdUser> implements UserService {

    /**
     * @param dto 登录用户信息对象
     * @return 登录结果
     * @Description admin登录功能
     */
    @Override
    public ResponseResult login(UserDto dto) {
        //1. 校验参数：用户名密码是否为空
        if (ObjectUtils.isEmpty(dto) || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustomException.custom(AppHttpCodeEnum.LOGIN_PARAM_ISNULL);
        }
        //2. 根据用户名精确查询有效的用户
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS)
        );
        if (ObjectUtils.isEmpty(adUser)) {
            CustomException.custom(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.比对密码
        String dataBasePwd = adUser.getPassword();
        String password = dto.getPassword();
        String salt = adUser.getSalt();
        // 加密规则： password+salt
        String saltPwd = password + salt;
        String digestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        if (!dataBasePwd.equals(digestPwd)) {
            CustomException.custom(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4. 更新数据库登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5. 生成Token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //6. 返回登录结果：用户信息和token信息
        Map<String, Object> result = new HashMap<>();
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(dto,userVo);
        result.put("token", token);
        result.put("user", userVo);
        return ResponseResult.okResult(result);
    }

    /**
     * @param adUser 用户实体对象
     * @return 注册结果
     * @Description 注册功能
     */
    @Override
    public ResponseResult register(AdUser adUser) {
        //1. 校验参数
        if (StringUtils.isEmpty(adUser.getName()) || StringUtils.isEmpty(adUser.getPassword())) {
            CustomException.custom(AppHttpCodeEnum.LOGIN_PARAM_ISNULL);
        }
        //2. 密码md5加密（密码+salt）
        String salt = RandomStringUtils.random(10) + "abc";
        String psw = salt+adUser.getPassword();
        adUser.setPassword(DigestUtils.md5DigestAsHex(psw.getBytes()));
        adUser.setSalt(salt);
        adUser.setCreatedTime(new Date());
        adUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
        save(adUser);
        return ResponseResult.okResult();
    }
}
